package poc.scc.dao.hibernate;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

@SuppressWarnings("unchecked")
public abstract class AbstractHibernateDao <T extends Serializable> {
	protected Class<T> clazz;

	@Autowired
	SessionFactory sessionFactory;
		
	public final void setClazz( Class< T > clazzToSet){
		this.clazz = clazzToSet;
	}


	public T find(Long id){
		Object obj = getCurrentSession().get(clazz, id );
		if(obj !=null) 
			return (T)obj;
		else
			return null;
	}
	public List<T> findAll(){
		return getCurrentSession().createQuery("from " + clazz.getName()).list();
	}

	public void create(T entity){
		getCurrentSession().persist(entity);
	}

	public T update(T entity){
		return (T)getCurrentSession().merge( entity );
	}

	public void delete(T entity){
		getCurrentSession().delete( entity );
	}
	public void deleteById(Long entityId ){
		T entity = find( entityId );
		delete( entity );
	}
	public T merge(T entity){
		return (T)getCurrentSession().merge(entity);
	}

	protected final Session getCurrentSession(){
		return sessionFactory.getCurrentSession();
	}
}
